<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

//俩个坐标点之间的距离
function getDistance($lon1, $lat1, $lon2, $lat2, $unit = 2, $decimal = 2)
{

    $EARTH_RADIUS = 6371.004; // 地球半径系数
    $PI = 3.1415926;
    $radLat1 = $lat1 * $PI / 180.0;
    $radLat2 = $lat2 * $PI / 180.0;
    $radLng1 = $lon1 * $PI / 180.0;
    $radLng2 = $lon2 * $PI / 180.0;
    $a = $radLat1 - $radLat2;
    $b = $radLng1 - $radLng2;
    $distance = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2)));
    $distance = $distance * $EARTH_RADIUS * 1000;
    if ($unit == 2) {
        $distance = $distance / 1000;
    }
    return round($distance, $decimal);
}

//生成推荐码
function createOrdersn()
{
    $code = time() . rand(100000, 999999);
    return $code;
}

function reordersn($model)
{
    $code = createOrdersn();
    $row = $model->where('ordersn', $code)->find();
    if ($row) {
        reordersn();
    } else {
        return $code;
    }
}


//生成订单号
function createPayOrdersn()
{
    $code = time() . rand(100000, 999999);
    return $code;
}

function repayorder($model)
{
    $code = createPayOrdersn();
    $row = $model->where('paymentid', $code)->find();
    if ($row) {
        repayorder();
    } else {
        return $code;
    }
}

//生成推荐码
function createorderCode()
{
    $code = rand(10000000, 99999999);
    return $code;
}

function orecode($user)
{
    $code = createorderCode();
    $row = $user->where('code', $code)->find();
    if ($row) {
        orecode();
    } else {
        return $code;
    }
}

//生成推荐码
function createCode()
{
    $code = rand(10000000, 99999999);
    return $code;
}

function recode($user)
{
    $code = createCode();
    $row = $user->where('code', $code)->find();
    if ($row) {
        recode();
    } else {
        return $code;
    }
}

function rsa_asr($rsa, $data = [])
{
    $MAX_DECRYPT_BLOCK = 172;
    $ct = "";
    $str = strlen($data);
    $offSet = 0;
    $endOffSet = $MAX_DECRYPT_BLOCK;
    while ($str - $offSet > 0) {
        if ($str - $offSet > $MAX_DECRYPT_BLOCK) {
            $bufTmp = substr($data, $offSet, $endOffSet);
            $ct .= $rsa->privDecrypt($bufTmp);
        } else {
            $bufTmp = substr($data, $offSet, $str);
            $ct .= $rsa->privDecrypt($bufTmp);
        }
        $offSet += $MAX_DECRYPT_BLOCK;
    }
    return json_decode($ct, true);
}



function unique()
{
    $code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $rand = $code[rand(0, 25)]
        . strtoupper(dechex(date('m')))
        . date('d') . substr(time(), -5)
        . substr(microtime(), 2, 5)
        . sprintf('%02d', rand(0, 99));
    for (
        $a = md5($rand, true),
        $s = '123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ',
        $d = '',
        $f = 0;
        $f < 8;
        $g = ord($a[$f]),
        $d .= $s[($g ^ ord($a[$f + 8])) - $g & 0x1F],
        $f++
    );
    return $d;
}

//1.数组转xml
function arrayToXml($arr)
{
    $xml = "<xml>";
    foreach ($arr as $key => $val) {
        if (is_numeric($val)) {
            $xml .= "<$key>$val</$key>";
        } else
            $xml .= "<$key><![CDATA[$val]]></$key>";
    }
    $xml .= "</xml>";
    return $xml;
}

//2.xml转数组
function xmlToArray($xml)
{
    $arr = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
    return $arr;
}


/**

 * excel表格导出

 * @param string $fileName 文件名称

 * @param array $headArr 表头名称

 * @param array $data 要导出的数据

 * @author static7  */

function excelExport($fileName = '', $headArr = [], $data = [])
{
    $date = date("Y_m_d", time());
    $fileName .= "_{$date}.xls";
    //创建PHPExcel对象，注意，不能少了\
    $objPHPExcel = new \PHPExcel();
    $objProps = $objPHPExcel->getProperties();
    //设置表头
    $key = 0;
    //print_r($headArr);exit;
    foreach ($headArr as $v) {
        //注意，不能少了。将列数字转换为字母\
        $colum = \PHPExcel_Cell::stringFromColumnIndex($key);
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum . '1', $v);
        $key += 1;
    }
    $column = 2;
    $objActSheet = $objPHPExcel->getActiveSheet();

    foreach ($data as $key => $rows) { //行写入
        $span = 0;
        foreach ($rows as $keyName => $value) { // 列写入
            $j = \PHPExcel_Cell::stringFromColumnIndex($span);
            $objActSheet->setCellValue($j . $column, $value);
            $span++;
        }
        $column++;
    }

    $fileName = iconv("utf-8", "gb2312", $fileName);
    //重命名表
    $objPHPExcel->getActiveSheet()->setTitle($date);
    //设置字体大小
    $objPHPExcel->getDefaultStyle()->getFont()->setSize(14);
    //设置单元格宽度
    $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(15);
    //设置默认行高
    $objPHPExcel->getActiveSheet()->getDefaultRowDimension()->setRowHeight(23);
    //设置活动单指数到第一个表,所以Excel打开这是第一个表
    $objPHPExcel->setActiveSheetIndex(0);
    header('Content-Type: application/vnd.ms-excel');
    header("Content-Disposition: attachment;filename=\"$fileName\"");
    header('Cache-Control: max-age=0');
    $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
    $objWriter->save('php://output'); //文件通过浏览器下载
    exit;
}

//导出操作
function outExcel($title, $data)
{
    $title = "商户清算对帐表" . date('Y-m-d H:i:s', time());
    $data = array(
        array(
            'name' => '数据1',
            'head' => array(
                '#商户分清对账',
                '#账单号20190417175906',
                '#起始日期：[2019年4月17日 00:00:00]终止日期：[2019年4月23日 00:00:00]',
                '#----------------------------------------------------------------------------财务明细列表----------------------------------------------------------------------------'
            ),
            'title' => array('标题1', '标题2', '标题3', '标题4', '标题5', '标题6', '标题7'),
            'content' => array(
                array('id' => '值1', 'name' => '值2', 'title' => '值3', 'del' => '值4', 'add' => '值5', 'rr' => '值6', 'hh' => '值7'),
                array('id' => '值1', 'name' => '值2', 'title' => '值3', 'del' => '值4', 'add' => '值5', 'rr' => '值6', 'hh' => '值7'),
                array('id' => '值1', 'name' => '值2', 'title' => '值3', 'del' => '值4', 'add' => '值5', 'rr' => '值6', 'hh' => '值7'),
            ),
            'floor' => array(
                '#--------------------------------------------------------------------------财务明细列表结束--------------------------------------------------------------------------',
                '#原始订单合计：56笔，共-6515216元',
                '#营销成本合计：56笔，共6515216元',
                '#导出时间：[2019年4月17日 00:00:00]',
            )
        ),
        array(
            'name' => '数据2',
            'head' => array(
                '#商户分清对账',
                '#账单号20190417175906',
                '#起始日期：[2019年4月17日 00:00:00]终止日期：[2019年4月23日 00:00:00]',
                '#----------------------------------------------------------------------------财务明细列表----------------------------------------------------------------------------'
            ),
            'title' => array('标题1', '标题2', '标题3', '标题4', '标题5', '标题6', '标题7'),
            'content' => array(
                array('id' => '值1', 'name' => '值2', 'title' => '值3', 'del' => '值4', 'add' => '值5', 'rr' => '值6', 'hh' => '值7'),
                array('id' => '值1', 'name' => '值2', 'title' => '值3', 'del' => '值4', 'add' => '值5', 'rr' => '值6', 'hh' => '值7'),
                array('id' => '值1', 'name' => '值2', 'title' => '值3', 'del' => '值4', 'add' => '值5', 'rr' => '值6', 'hh' => '值7'),
                array('id' => '值1', 'name' => '值2', 'title' => '值3', 'del' => '值4', 'add' => '值5', 'rr' => '值6', 'hh' => '值7'),
            ),
            'floor' => array(
                '#--------------------------------------------------------------------------财务明细列表结束--------------------------------------------------------------------------',
                '#原始订单合计：56笔，共-6515216元',
                '#营销成本合计：56笔，共6515216元',
                '#导出时间：[2019年4月17日 00:00:00]',
            )
        ),
    );
    $alphabets = array(
        'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
        'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV', 'AW', 'AX', 'AY', 'AX',
    );

    //引入导出phpexcel
    Vendor('PHPExcel.PHPExcel#class');
    Vendor('PHPExcel.PHPExcel.IOFactory');

    // Create new PHPExcel object
    $objPHPExcel = new \PHPExcel();

    // Set properties
    $objPHPExcel->getProperties()->setCreator("Maarten Balliauw")
        ->setLastModifiedBy("Maarten Balliauw")
        ->setTitle("Office 2007 XLSX Test Document")
        ->setSubject("Office 2007 XLSX Test Document")
        ->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
        ->setKeywords("office 2007 openxml php")
        ->setCategory($title);

    //setCellValue($a,$v)赋值到单元格  $a:单元格表头如：A2   $v:单元格值
    //mergeCells($a) 合并单元格    $a:单元格表头如：A2:Z2
    foreach ($data as $k => $v) {
        $objPHPExcel->createSheet();
        $objPHPExcel->setActiveSheetIndex($k);
        foreach ($v['head'] as $ka => $va) {
            $mergeCells = "A" . ($ka + 1) . ":Z" . ($ka + 1);
            $objPHPExcel->getActiveSheet($k)->mergeCells($mergeCells);
            $objPHPExcel->setActiveSheetIndex($k)->setCellValue($alphabets[0] . ($ka + 1), $va);
        }
        foreach ($v['title'] as $kb => $vb) {
            // $objPHPExcel->getActiveSheet()->getStyle($alphabets[$kb].(count($v['head'])+1))->getFont()->setBold(true);//加粗
            $objPHPExcel->setActiveSheetIndex($k)->setCellValue($alphabets[$kb] . (count($v['head']) + 1), $vb);
        }
        $res = array_values($v['content']);
        foreach ($res as $kc => $vc) {
            $countA = (count($v['head']) + 2 + $kc);
            $item = array_values($vc);
            for ($i = 0; $i < count($item); $i++) {
                $contentAlphabets = $alphabets[$i] . $countA;
                $objPHPExcel->setActiveSheetIndex($k)->setCellValue($contentAlphabets, $item[$i] . " ");
            }
        }
        foreach ($v['floor'] as $kd => $vd) {
            $count = (count($v['head']) + count($v['content']) + 2 + $kd);
            $mergeCells = "A" . $count . ":Z" . $count;
            $objPHPExcel->getActiveSheet($k)->mergeCells($mergeCells);
            $floorAlphabets = $alphabets[0] . $count;
            $objPHPExcel->setActiveSheetIndex($k)->setCellValue($floorAlphabets, $vd);
        }
        $objPHPExcel->getActiveSheet()->setTitle($v['name']);
    }
    //设置单元格宽度
    foreach ($alphabets as $k => $v) {
        $objPHPExcel->getActiveSheet()->getColumnDimension($v)->setWidth(30);
    }

    $objPHPExcel->setActiveSheetIndex(0);
    // exit;
    header('Content-Type: application/vnd.ms-excel');
    header("Content-Disposition: attachment;filename=$title.xls");
    header('Cache-Control: max-age=0');

    // $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
    $objWriter = new \PHPExcel_Writer_Excel5($objPHPExcel);

    $objWriter->save('php://output');
}



function api_curl($url, $data = false, $ispost = 0)
{
    $headers = array();
    array_push($headers, "Content-Type" . ":" . "application/x-www-form-urlencoded; charset=UTF-8");
    $httpInfo = array();
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 300);
    curl_setopt($ch, CURLOPT_TIMEOUT, 300);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_FAILONERROR, false);
    if (1 == strpos("$" . $url, "https://")) {
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    }
    if ($ispost) {
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_URL, $url);
    } else {
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
        $data = http_build_query($data);
        if ($data) {
            curl_setopt($ch, CURLOPT_URL, $url . '?' . $data);
        } else {
            curl_setopt($ch, CURLOPT_URL, $url);
        }
    }
    $response = curl_exec($ch);
    if ($response === FALSE) {
        return false;
    }
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $httpInfo = array_merge($httpInfo, curl_getinfo($ch));
    curl_close($ch);
    $response = json_decode($response, true);
    return $response;
}
